#!/usr/bin/env python
'''
A simple serial logger for the shell firmware
messages.
'''
import sys
import tos as tinyos
import logging

# ----------------------------------------------------------------------------- 
# logging configuration
# ----------------------------------------------------------------------------- 
logging.basicConfig()
log = logging.getLogger()

# ----------------------------------------------------------------------------- 
# Classes
# ----------------------------------------------------------------------------- 
class ShellMessage(tinyos.Packet):

    Type = 0x06
    Labels = ['light', 'light', 'audio', 'ir', 'temp', 'accx', 'accy', 'magx', 'magy']

    def __init__(self, packet = None):
        ''' Initialize a new instance of the ShellMessage

        :param packet: The packet to parse
        '''
        settings = [
            ('id',       'int', 2),
            ('counter',  'int', 2),
            ('readings', 'blob', None)]
        tinyos.Packet.__init__(self, settings, packet)

    def parse(self):
        ''' Return the parsed data packet

        :returns: The parsed data packet as a dict
        '''
        values = [(i<<8 | j) for (i,j) in zip(self.readings[::2], self.readings[1::2])]
        return dict(zip(self.Labels, values))

# ----------------------------------------------------------------------------- 
# Main Runner
# ----------------------------------------------------------------------------- 
sys.argv = ['', 'serial@/dev/ttyUSB0:115200']
messages = tinyos.AM()

while True:
    packet = messages.read()
    log.debug(packet)
    if packet and (packet.type == ShellMessage.Type):
        message = ShellMessage(packet.data)
        log.debug(message)
        print message.parse()
        #print "Message(%d, %d) data:" %  (message.id, message.counter)
        #print [i<<8 | j for (i,j) in zip(message.readings[::2], messages.readings[1::2])]

